/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Mar 15, 2012  2:49:50 PM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : sap.business.sd.outbound
 * File Name : VwSyncMktCustomerService.java
 * TODO
 */
package sap.business.sd.outbound;

import java.util.ArrayList;
import java.util.List;
import jpa.entitys.synchro.staging.SdCustomerOutb1;
import jpa.service.common.SessionEntityManager;
import jpa.service.synchro.staging.SdCustomerOutb1Services;
import org.apache.log4j.Logger;
import promis.utility.CommonService;
import sap.business.commons.SynchroOutAbstract;
import sap.business.commons.services.CommonJCOReturn;
import sap.jco.client.Connection;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoTable;

/**
 * @author chatree
 *
 */
public class VwSyncMktCustomerService extends SynchroOutAbstract {
	
	private static final Logger log = Logger.getLogger(VwSyncMktCustomerService.class);
	private SdCustomerOutb1Services SdCustomerOutb1Serv = null; 

	/**
	 * Date =Nov 12, 2013 : 2:27:57 PM 
	 * CreateBy=Chatree Siangklom
	 * VwSyncMktCustomerService
	 * TODO
	 */
	public VwSyncMktCustomerService() {
		try {
			this.sap_bapi = "ZIN_SD_CUSTOMER_MAINTAIN";
			this.sap_table = "CUSTOMER";
			this.sap_table_return = "RETURN";
			super.emSynchro = new SessionEntityManager().CreatedEntityManager();			
		} catch (Exception e) {
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}
	}
	
	@Override
	public void SynchroToSap(JCoFunction jcoFunction, JCoTable jcoTable, List<?> value_list) throws Exception {
		// TODO Auto-generated method stub
		//Check Is not isEmpty is exit method.
		if(!jcoTable.isEmpty())
		{
			log.info("Bapi = "+ sap_bapi +", table "+ sap_table +" is not Empty ");
			return;
		}	
		
		if(!CommonService.IsNull(value_list)){
			log.info("value_list.size : " + value_list.size());			
			log.info("table.getNumRows : " + jcoTable.getNumRows());
			
			for (Object obj : value_list) 
	        {
				SdCustomerOutb1 model = (SdCustomerOutb1)obj;
				log.info("InstanceNo = " + model.getInstanceNo() + " -- PROMIS_TXN_ID = " +  model.getPromisStagingId());
				
				jcoTable.appendRow();
				jcoTable.setValue("PROMIS_TXN_ID", model.getPromisStagingId());
				jcoTable.setValue("INTERFACE_NO", "SDI01");
				jcoTable.setValue("PROMIS_CUSNO", model.getCustomerCode());
				jcoTable.setValue("NAME1", model.getCustomerName());
				jcoTable.setValue("DATE_BIRTH", model.getDateOfBirth());
				jcoTable.setValue("STRAS1", model.getBillingAddress());
				jcoTable.setValue("CITY", model.getCity());
				jcoTable.setValue("DISTRICT", model.getDistrict()); 			
				jcoTable.setValue("POSTL_COD1", model.getZipCode());				
				jcoTable.setValue("ADDR_FLAG", model.getAddrFlag());				
				jcoTable.setValue("PROMIS_ADDRKEY", model.getBillingAddressCode());
				jcoTable.setValue("BUILDING", "");
				jcoTable.setValue("FLOOR", "");
				jcoTable.setValue("ROOM_NO", "");
				jcoTable.setValue("COUNTRY", model.getCountryCode());
				jcoTable.setValue("TEL1_NUMBR", model.getPhoneNumber());
				jcoTable.setValue("TEL1_EXT", model.getExtNumber());
				jcoTable.setValue("MOBILE_PHONE", model.getMobile());
				jcoTable.setValue("FAX_NUMBER", model.getFaxNumber());
				jcoTable.setValue("FAX_EXTENS", model.getFaxExtens());
				jcoTable.setValue("E_MAIL", model.getEMail());
				jcoTable.setValue("CURRENCY", "THB");
				jcoTable.setValue("PERSONAL_ID", model.getIdNo());
				jcoTable.setValue("TAX_ID", model.getTaxId());
				jcoTable.setValue("PAYMENT_TERM", "");
				
	        }
		}
		
		super.SynchroToSap(jcoFunction, jcoTable, value_list);
		
	}
	
	@Override
	public void CallbackMessageFromSap(JCoTable jcoTable_return) throws Exception {
		// TODO Auto-generated method stub
		
		List<SdCustomerOutb1> lst = new ArrayList<SdCustomerOutb1>();				
		if(jcoTable_return != null && jcoTable_return.isEmpty() == false)
		{
			log.info("Update Message table Retrun getNumRows = " + jcoTable_return.getNumRows());
			for(int i = 0; i < jcoTable_return.getNumRows(); i++)
			{
				jcoTable_return.setRow(i);
				SdCustomerOutb1 model = SdCustomerOutb1Serv.findById(CommonService.IsNullRNull(jcoTable_return.getString("PROMIS_TXN_ID")));
				log.info(CommonJCOReturn.toString(jcoTable_return));
				
				if(model != null){
					model.setMsgCode(CommonService.IsNullRNull(jcoTable_return.getString("MSG_CODE")));
					model.setMsgDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_DESC")));
					model.setMsgAltDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ALT_DESC")));
					model.setMsgActResult(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ACTION_RESULT")));
					model.setIsactive("Y");
					model.setIssync("Y");
					
					lst.add(model);
				}
			}
			
			SdCustomerOutb1Serv.Updated(lst);
		}else
			log.info(CommonJCOReturn.toString(jcoTable_return));
		
		super.CallbackMessageFromSap(jcoTable_return);
	}
	
	private void UpdateStagingWhenError(List<SdCustomerOutb1> value_list, Exception error) throws Exception{
		log.info("Start UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		try{
			
			if(!CommonService.IsNull(value_list)){
				List<SdCustomerOutb1> newlst = new ArrayList<SdCustomerOutb1>();
				for(SdCustomerOutb1 model : value_list)
				{				
					model.setMsgCode("E");
					model.setMsgDesc(CommonService.CutString(error.getMessage(), 3500));
					model.setIsactive("Y");
					model.setIssync("N");
					newlst.add(model);
				}
				
				new SdCustomerOutb1Services(this.emSynchro).Updated(newlst);
			}
			
		}catch(Exception e){
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}finally{
			log.info("End UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		}
	}
	
	public void SendingToSAP(String customerCode, String issync) throws Exception {
		log.info(" Customer Start ");
		try{
			
			this.jco_conn  = new Connection();

			//Get SAP BAPI function
			JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
			
			//Get SAP Staging table
			JCoTable jcoTable = jco_conn.getTables(sap_table);
			SdCustomerOutb1Serv = new SdCustomerOutb1Services(this.emSynchro);
			List<SdCustomerOutb1> value_list = SdCustomerOutb1Serv.findByCustomerCode(customerCode, "A", issync);
			
			if(!CommonService.IsNull(value_list))
			{
				SynchroToSap(jcoFunction, jcoTable, value_list);
				
				//Get SAP Staging table retrun message
				JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
				CallbackMessageFromSap(jcoTable_return);
				
			}else
				log.warn("findByCustomerCode  :::  find not found Customer ");
			
			
		}catch(Exception e)
		{
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}
	}
	
	public void SendingToSAP(List<SdCustomerOutb1> value_list) throws Exception {		
		try{
			
			if(!CommonService.IsNull(value_list))
			{
				this.jco_conn  = new Connection();

				//Get SAP BAPI function
				JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
				
				//Get SAP Staging table
				JCoTable jcoTable = jco_conn.getTables(sap_table);
				SdCustomerOutb1Serv = new SdCustomerOutb1Services(this.emSynchro);
				
				//List<SdCustomerOutb1> value_list = SdCustomerOutb1Serv.findAllIsSync("N");
				SynchroToSap(jcoFunction, jcoTable, value_list);
				
				//Get SAP Staging table retrun message
				JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
				CallbackMessageFromSap(jcoTable_return);
			}		
		}catch(Exception e)
		{
			UpdateStagingWhenError(value_list, e);
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}	
	}
	
	@Deprecated
	private void Start() throws Exception
	{
		
		this.jco_conn  = new Connection();

		//Get SAP BAPI function
		JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
		
		//Get SAP Staging table
		JCoTable jcoTable = jco_conn.getTables(sap_table);
		SdCustomerOutb1Serv = new SdCustomerOutb1Services(this.emSynchro);
		List<SdCustomerOutb1> value_list = SdCustomerOutb1Serv.findAllIsSync("N");
		SynchroToSap(jcoFunction, jcoTable, value_list);
		
		//Get SAP Staging table retrun message
		JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
		CallbackMessageFromSap(jcoTable_return);
	}

//	/**
//	 * @param args
//	 */
//	public static void main(String[] args) {
//		// TODO Auto-generated method stub
//		
//		try{
//			
//			VwSyncMktCustomerService obj = new VwSyncMktCustomerService();
//			
//			obj.Start();
//			
//		}catch(Exception ex){
//			log.error(ex);
//		}
//
//	}

}
